W12_API 自己做 [ BE101 ] 實作之二


Posted by Christy on 2021-08-30

實作 API 串接

BE101_真正的實戰:留言板 - API 篇_前端串接 API

剛剛那兩個檔案,api_add_comment.php, api_comments.php 就是我們自己寫的 api,現在我們要串接這兩個檔案

  1. 先從 index.php 複製一個檔案叫 api_demo.php

目的是要把留言板輸入留言,以及下面顯示留言的版型直接拿來用

  1. 0 - 1':40" 把所有 php 相關的程式碼都刪掉,只保留版型就好

  2. 1':41" - 3'48" 用 ajax 的方式,把資料拿出來

可以去 You might not need jQuery 裡面把 XML 那個 open, onload, send 的程式碼撈出來

<script>
  function getComments(cb) {
    var request = new XMLHttpRequest()
    request.open('GET', 'api_comments.php', true)

    request.onload = function() {
      if (this.status >= 200 && this.status < 400) {
        var resp = this.response
        var json = JSON.parse(resp)
        console.log(json
       } 
     };
     request.send();
    }

  getComments();
</script>
  1. 3'51" - 7'45" 顯示留言功能實作

拿到資料以後呢,就跟 w7 一樣,用 DOM 語法把資料動態放到網頁上

<script>
  var request = new XMLHttpRequest();
  request.open('GET', 'api_comments.php', true);

  request.onload = function() {
  if (this.status >= 200 && this.status < 400) {
  var resp = this.response;
  var json = JSON.parse(resp)
  var comments = json.comments

   for (i=0; i<comments.length; i++) {
     var comment = comments[i]
     var div = document.createElement('div')
     div.classList.add('card')
     div.innerHTML = `
       <div class="card">
         <div class="card__avatar">
       </div>
       <div class="card__body">
         <div class="card__info">
           <span class="card__author">${comment.nickname}(@${comment.username})
           </span>
           <span class="card__time">${comment.created_at}
           </span>
         </div>
         <p class="card__content">${comment.content}</p>
         </div>
       </div>
`
document.querySelector('section').appendChild(div)
    }
  } 
};
  request.send();
</script>
  1. 7'46" - end 新增留言

a. 首先就是先攔截表單預設行為

b. 接著抓留言內容

var content = document.querySelector('textarea[name=content]').value

c. 用 js 方式把資料送出,就看新增留言了

再 new 一個 XML,然後 open, onload, send

d. 記得要把輸入內容做編碼,就是解決 a&b=1 之類的東西

encodeURIComponent()

e. XSS 問題,google 關鍵字「escape() xss js」,可以找到下面一段程式碼,再把內容那邊加上去就好了,不能用 escape()

function encodeHTML(s) {
  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}

遇到困難:

  1. 發現每次要看 dev 的 console 紀錄都一大堆東西,原來在設定那邊把 selected context only 勾起來,輸出就比較單純了

  2. 我終於知道要怎麼解決程式碼亂七八糟的問題了,就是 sublime 右下角設定不可以設成 tab 啦,要設成 space










Related Posts

CSS split four squares

CSS split four squares

Day 108

Day 108

14. Chain of Responsibility

14. Chain of Responsibility


Comments